<?php

namespace RjYst\ExcelExport\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use RjYst\ExcelExport\Services\PackageChecker;

class InstallExcelExportCommand extends Command
{
    protected $signature = 'rj:install-excel-export {--force : 强制覆盖已存在的文件}';
    protected $description = 'Install RjYst Excel Export Package';

    public function handle()
    {
        $this->info('📊 开始安装 RjYst Excel Export Package...');

        // 1. 检查并安装 maatwebsite/excel
        $this->checkAndInstallExcelPackage();

        // 2. 发布配置文件
        $this->publishConfig();

        // 3. 创建导出文件
        $this->createExportFiles();

        // 4. 创建控制器
        $this->createExportController();

        // 5. 创建 Action
        $this->createDataExportAction();

        // 6. 更新路由
        $this->updateRoutes();

        // 7. 完成提示
        $this->displaySuccessMessage();
    }

    protected function checkAndInstallExcelPackage()
    {
        $this->info('📦 检查 maatwebsite/excel 包...');

        $result = PackageChecker::ensurePackageInstalled('maatwebsite/excel');

        if ($result['action'] === 'skipped') {
            $this->info('ℹ️ ' . $result['message']);
        } elseif ($result['action'] === 'installed') {
            $this->info('✅ ' . $result['message']);
        } else {
            $this->error('❌ ' . $result['message']);
        }
    }

    protected function publishConfig()
    {
        $this->info('⚙️ 发布配置文件...');

        $this->call('vendor:publish', [
            '--tag' => 'rj-excel-export-config',
            '--force' => $this->option('force')
        ]);

        $this->info('✅ 配置文件发布完成');
    }

    protected function createExportFiles()
    {
        $this->info('📝 创建导出文件...');

        // 创建 CategorySheet
        $this->createCategorySheet();

        // 创建 CategoryExport
        $this->createCategoryExport();

        $this->createClickLearnSheet();
        $this->createClickLearnSpellSheet();
        $this->createClickLearnExport();
        //常用表达法
        $this->createSentenceSheet();
        $this->createSentenceExport();

        //背单词
        $this->createLearnWordSheet();
        $this->createLearnWordExport();

        //歌曲歌谣
        $this->createTextbookAudioSheet();
        $this->createTextbookAudioExport();

        //情境学习
        $this->createVirtualSheet();
        $this->createVirtualWordSheet();
        $this->createVirtualExport();

        //单元词汇表
        $this->createVocabularySheet();
        $this->createVocabularyExport();

    }

    protected function createCategorySheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/CategorySheet.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($sheetPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ CategorySheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('CategorySheet.php', $sheetFile);
        $this->info('✅ 创建文件: CategorySheet.php');
    }
    protected function createClickLearnSheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/ClickLearnSheet.php';

        PackageChecker::ensureDirectoryExists($sheetPath);

        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ ClickLearnSheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('ClickLearnSheet.php', $sheetFile);
        $this->info('✅ 创建文件: ClickLearnSheet.php');
    }

    protected function createVocabularyExport()
    {
        $exportPath = app_path('Admin/Exports');
        $exportFile = $exportPath . '/VocabularyExport.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($exportPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($exportFile) && !$this->option('force')) {
            $this->info('ℹ️ VocabularyExport.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('VocabularyExport.php', $exportFile);
        $this->info('✅ 创建文件: VocabularyExport.php');
    }
    protected function createVirtualExport()
    {
        $exportPath = app_path('Admin/Exports');
        $exportFile = $exportPath . '/VirtualExport.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($exportPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($exportFile) && !$this->option('force')) {
            $this->info('ℹ️ VirtualExport.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('VirtualExport.php', $exportFile);
        $this->info('✅ 创建文件: VirtualExport.php');
    }
    protected function createTextbookAudioExport()
    {
        $exportPath = app_path('Admin/Exports');
        $exportFile = $exportPath . '/TextbookAudioExport.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($exportPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($exportFile) && !$this->option('force')) {
            $this->info('ℹ️ TextbookAudioExport.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('TextbookAudioExport.php', $exportFile);
        $this->info('✅ 创建文件: TextbookAudioExport.php');
    }
    protected function createLearnWordExport()
    {
        $exportPath = app_path('Admin/Exports');
        $exportFile = $exportPath . '/LearnWordExport.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($exportPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($exportFile) && !$this->option('force')) {
            $this->info('ℹ️ LearnWordExport.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('LearnWordExport.php', $exportFile);
        $this->info('✅ 创建文件: LearnWordExport.php');
    }
    protected function createSentenceExport()
    {
        $exportPath = app_path('Admin/Exports');
        $exportFile = $exportPath . '/SentenceExport.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($exportPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($exportFile) && !$this->option('force')) {
            $this->info('ℹ️ SentenceExport.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('SentenceExport.php', $exportFile);
        $this->info('✅ 创建文件: SentenceExport.php');
    }

    protected function createVirtualWordSheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/VirtualWordSheet.php';

        PackageChecker::ensureDirectoryExists($sheetPath);

        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ VirtualWordSheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('VirtualWordSheet.php', $sheetFile);
        $this->info('✅ 创建文件: VirtualWordSheet.php');
    }
    protected function createVocabularySheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/VocabularySheet.php';

        PackageChecker::ensureDirectoryExists($sheetPath);

        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ VocabularySheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('VocabularySheet.php', $sheetFile);
        $this->info('✅ 创建文件: VocabularySheet.php');
    }

    protected function createVirtualSheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/VirtualSheet.php';

        PackageChecker::ensureDirectoryExists($sheetPath);

        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ VirtualSheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('VirtualSheet.php', $sheetFile);
        $this->info('✅ 创建文件: VirtualSheet.php');
    }
    protected function createTextbookAudioSheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/TextbookAudioSheet.php';

        PackageChecker::ensureDirectoryExists($sheetPath);

        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ TextbookAudioSheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('TextbookAudioSheet.php', $sheetFile);
        $this->info('✅ 创建文件: TextbookAudioSheet.php');
    }
    protected function createLearnWordSheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/LearnWordSheet.php';

        PackageChecker::ensureDirectoryExists($sheetPath);

        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ LearnWordSheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('LearnWordSheet.php', $sheetFile);
        $this->info('✅ 创建文件: LearnWordSheet.php');
    }


    protected function createSentenceSheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/SentenceSheet.php';

        PackageChecker::ensureDirectoryExists($sheetPath);

        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ SentenceSheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('SentenceSheet.php', $sheetFile);
        $this->info('✅ 创建文件: SentenceSheet.php');
    }
    protected function createClickLearnSpellSheet()
    {
        $sheetPath = app_path('Admin/Exports/Sheet');
        $sheetFile = $sheetPath . '/ClickLearnSpellSheet.php';

        PackageChecker::ensureDirectoryExists($sheetPath);

        if (PackageChecker::fileExists($sheetFile) && !$this->option('force')) {
            $this->info('ℹ️ ClickLearnSheet.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('ClickLearnSpellSheet.php', $sheetFile);
        $this->info('✅ 创建文件: ClickLearnSpellSheet.php');
    }
    protected function createCategoryExport()
    {
        $exportPath = app_path('Admin/Exports');
        $exportFile = $exportPath . '/CategoryExport.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($exportPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($exportFile) && !$this->option('force')) {
            $this->info('ℹ️ CategoryExport.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('CategoryExport.php', $exportFile);
        $this->info('✅ 创建文件: CategoryExport.php');
    }
    protected function createClickLearnExport()
    {
        $exportPath = app_path('Admin/Exports');
        $exportFile = $exportPath . '/ClickLearnExport.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($exportPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($exportFile) && !$this->option('force')) {
            $this->info('ℹ️ ClickLearnExport.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('ClickLearnExport.php', $exportFile);
        $this->info('✅ 创建文件: ClickLearnExport.php');
    }
    protected function createExportController()
    {
        $this->info('🎮 创建导出控制器...');

        $controllerPath = app_path('Admin/Controllers/Export');
        $controllerFile = $controllerPath . '/ExcelExportController.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($controllerPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($controllerFile) && !$this->option('force')) {
            $this->info('ℹ️ ExcelExportController.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('ExcelExportController.php', $controllerFile);
        $this->info('✅ 创建文件: ExcelExportController.php');
    }

    protected function createDataExportAction()
    {
        $this->info('⚡ 创建数据导出 Action...');

        $actionPath = app_path('Admin/Actions/Category');
        $actionFile = $actionPath . '/DataExport.php';

        // 确保目录存在
        PackageChecker::ensureDirectoryExists($actionPath);

        // 检查文件是否存在
        if (PackageChecker::fileExists($actionFile) && !$this->option('force')) {
            $this->info('ℹ️ DataExport.php 已存在，跳过创建');
            return;
        }

        $this->copyTemplateFile('DataExport.php', $actionFile);
        $this->info('✅ 创建文件: DataExport.php');
    }

    protected function copyTemplateFile(string $templateName, string $destination)
    {
        $templatePath = __DIR__ . '/../../Templates/' . $templateName;

        if (File::exists($templatePath)) {
            File::copy($templatePath, $destination);
        } else {
            $this->warn("⚠️ 模板文件不存在: {$templateName}");
        }
    }

    protected function updateRoutes()
    {
        $this->info('🔗 更新路由文件...');

        $routesFile = app_path('Admin/routes.php');

        if (!File::exists($routesFile)) {
            $this->createBasicRoutesFile($routesFile);
            return;
        }

        $routes = File::get($routesFile);

        // 检查是否已经包含导出路由
        if (str_contains($routes, "get('/dataExport'") || str_contains($routes, 'Export\\ExcelExportController@dataExport')) {
            $this->info('ℹ️ 导出路由已存在，跳过更新');
            return;
        }

        // 要添加的路由
        $newRoute = "    Route::get('/dataExport', 'Export\\ExcelExportController@dataExport');";

        // 查找 Route::group 中的 function 块
        $pattern = '/(Route::group\(\[[\s\S]*?\], function \(\) \{)([\s\S]*?)(\}\);)/';

        if (preg_match($pattern, $routes, $matches)) {
            $beforeGroup = $matches[1];
            $insideGroup = $matches[2];
            $afterGroup = $matches[3];

            // 在 function 块内部添加路由
            $updatedInside = $insideGroup;

            // 如果内部是空的或只有注释，直接添加
            if (trim(preg_replace('/\/\/.*/', '', $insideGroup)) === '') {
                $updatedInside = "\n" . $newRoute . "\n";
            } else {
                // 在末尾添加新路由
                $updatedInside = rtrim($insideGroup) . "\n" . $newRoute . "\n";
            }

            $newRoutes = $beforeGroup . $updatedInside . $afterGroup;

            File::put($routesFile, $newRoutes);
            $this->info('✅ 路由文件更新完成');
        } else {
            // 如果找不到标准格式，尝试在文件末尾前添加
            $this->addRouteAtEnd($routes, $newRoute);
        }
    }

    /**
     * 在文件末尾添加路由（备用方法）
     */
    protected function addRouteAtEnd($routes, $newRoute)
    {
        // 查找最后一个 Route::group 结束的位置
        $lastPos = strrpos($routes, '});');

        if ($lastPos !== false) {
            // 在最后一个 }); 之前添加路由
            $beforeEnd = substr($routes, 0, $lastPos);
            $afterEnd = substr($routes, $lastPos);

            $newRoutes = $beforeEnd . $newRoute . "\n" . $afterEnd;

            File::put(app_path('Admin/routes.php'), $newRoutes);
            $this->info('✅ 路由文件更新完成（备用方法）');
        } else {
            $this->warn('⚠️ 无法自动添加路由，请手动添加以下路由到 routes/admin.php:');
            $this->line($newRoute);
        }
    }

    protected function createBasicRoutesFile($routesFile)
    {
        // 确保目录存在
        PackageChecker::ensureDirectoryExists(dirname($routesFile));

        $content = <<<PHP
<?php

use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Route;
use Dcat\Admin\Admin;

Admin::routes();

Route::group([
    'prefix'     => config('admin.route.prefix'),
    'namespace'  => config('admin.route.namespace'),
    'middleware' => config('admin.route.middleware'),
], function (Router \$router) {

    \$router->get('/', 'HomeController@index');

});
PHP;

        File::put($routesFile, $content);
        $this->info('✅ 创建基础路由文件');
    }

    protected function displaySuccessMessage()
    {
        $this->info('🎉 RjYst Excel Export Package 安装完成！');
        $this->line('');
        $this->line('📁 生成的文件：');
        $this->line('   - app/Admin/Exports/Sheet/CategorySheet.php');
        $this->line('   - app/Admin/Exports/CategoryExport.php');
        $this->line('   - app/Admin/Controllers/Export/ExcelExportController.php');
        $this->line('   - app/Admin/Actions/Category/DataExport.php');
        $this->line('   - config/rj-excel-export.php');
        $this->line('');
        $this->line('📦 依赖包：');
        $this->line('   - maatwebsite/excel');
        $this->line('');
        $this->line('🔗 新增路由：');
        $this->line('   - GET /admin/dataExport');
        $this->line('');
        $this->line('💡 使用方法：');
        $this->line('   在控制器的 grid 方法中添加：');
        $this->line('   $grid->tools(new \\App\\Admin\\Actions\\Category\\DataExport(\'导出数据\', \'/skuCategoryExport\'));');
        $this->line('');
        $this->line('🔧 配置文件：');
        $this->line('   编辑 config/rj-excel-export.php 进行自定义配置');
        $this->line('');
        $this->warn('⚠️ 注意事项：');
        $this->warn('   1. 确保 Category 模型路径正确');
        $this->warn('   2. 根据需要调整导出字段和格式');
        $this->warn('   3. 可以扩展更多导出类型');
    }
}
